package com.spirit.mypopup.menu;

import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import com.spirit.mypopup.R;
import com.spirit.mypopup.menu.adapter.BaseMenuAdapter;
import com.spirit.mypopup.menu.adapter.BaseMenuFragment;
import com.spirit.mypopup.menu.adapter.OnSelectItemListener;

import java.util.HashMap;
import java.util.Map;

/**
 * author : fang.zhang
 * e-mail : initzf@126.com
 * date   : 2020/5/16
 * desc   :
 */
public class FilterMenuBar extends LinearLayout {
    private static final String TAG = "MyMenu";

    private int mId;
    private ViewGroup systemParent;
    private FrameLayout layout;
    private OnSelectItemListener onSelectItemListener;

    public FilterMenuBar(Context context) {
        this(context, null);
    }

    public FilterMenuBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FilterMenuBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(LinearLayout.HORIZONTAL);
    }

    private int pxToDp(int px) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, px, getResources().getDisplayMetrics());
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(pxToDp(55), MeasureSpec.EXACTLY));
    }


    public FilterMenuBar setDatas(BaseMenuAdapter... adapters) {
        if (adapters == null) {
            return this;
        }
        setWeightSum(adapters.length);
        fragmentMap = new HashMap<>();
        initView();

        for (BaseMenuAdapter adapter : adapters) {
            createTitleView(adapter);
        }
        return this;
    }

    private void createTitleView(BaseMenuAdapter adapter) {
        ViewGroup view = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.item_layout, null);

        LinearLayout.LayoutParams params = new LayoutParams(0, LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER;
        params.weight = 1;
        view.setLayoutParams(params);

        final TextView mTextView = view.findViewById(R.id.tvTitle);
        mTextView.setText(adapter.getTitle().getValue());
        addView(view);

        mTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                executeFragment(adapter,mTextView);
            }
        });
    }

    private void executeFragment(BaseMenuAdapter adapter,TextView mTextView) {
        BaseMenuFragment mFragment = fragmentMap.get(adapter.getTitle().getValue());

        if (mFragment == null) {
            mFragment = adapter.getFragment();
            mFragment.setOnSelectItemListener(new OnSelectItemListener() {
                @Override
                public void onSelectItemListener(OptionObject optionObj) {
                    onSelectItemListener.onSelectItemListener(optionObj);
                    mTextView.setText(optionObj.getTitle());
                    hiddleMenu();
                }
            });
            fragmentMap.put(adapter.getTitle().getValue(), mFragment);
        }

        if (systemParent.findViewById(mId) == null) {
            systemParent.addView(layout);
        }

        if (layout.getVisibility() == View.INVISIBLE) {
            layout.setVisibility(View.VISIBLE);
        }

        switchFragment(mFragment);
    }

    public void setOnSelectItemListener(OnSelectItemListener onSelectItemListener) {
        this.onSelectItemListener = onSelectItemListener;
    }

    private Map<String, BaseMenuFragment> fragmentMap;

    private Fragment mContent;

    private void switchFragment(Fragment to) {

        FragmentActivity activity = (FragmentActivity) getContext();

        final FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();

        if (mContent != to) {
            if (!to.isAdded()) {    // 先判断是否被add过
                if (mContent == null) {
                    ft.add(mId, to, to.getClass().getSimpleName()).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                } else {
                    ft.hide(mContent).add(mId, to, to.getClass().getSimpleName()).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                }
            } else {
                ft.hide(mContent).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
            mContent = to;
        }
    }

    private void initView() {
        FragmentActivity activity = (FragmentActivity) getContext();

        View decorView = activity.getWindow().getDecorView();
        systemParent = decorView.findViewById(android.R.id.content);

        mId = View.generateViewId();

        layout = new FrameLayout(activity);
        layout.setId(mId);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.topMargin = getBottom();
        layout.setLayoutParams(layoutParams);
        //layout.setBackgroundColor(ContextCompat.getColor(activity, R.color.color_90ffffff));
        layout.setBackgroundColor(ContextCompat.getColor(activity, R.color.menu_bj_color));

        layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                hiddleMenu();
            }
        });
    }

    public void hiddleMenu() {
        if (layout != null) {
            layout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (layout != null) {
            layout.removeAllViews();
        }
        if (systemParent != null) {
            systemParent.removeView(layout);
        }

        if (onSelectItemListener != null) {
            onSelectItemListener = null;
        }

        if (fragmentMap != null) {
            fragmentMap.clear();
        }
        mContent = null;
        layout = null;
        removeAllViews();
    }
}
